// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// S [author] rhyme_lph
// c [email]  rhymelph@gmail.com
// c [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/ocr_attachment_entity.dart';
import 'package:finance_app/src/http_service/http_asset_service.dart';
import 'package:finance_app/src/mixin/from_attach_mixin.dart';
import 'package:finance_app/src/provider/all_reports/fixed_asset/new_fixed_asset_provider.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/widgets/bottom_sheet/calendar_bottom_sheet.dart';
import 'package:flutter/material.dart';

import '../date_report_provider.dart';

class DisposalOfFixedAssetProvider extends BaseProvider with FormAttachMixin {
  DateTime disposalDate = DateTime.tryParse(Config.currentFY.endDate);
  List<OcrAttachmentEntity> attachedFiles;

  TextEditingController notesController = TextEditingController();
  FocusNode notesFocusNode = FocusNode();

  bool isEdit = true;

  int id;

  @override
  Future get dataFuture => null;

  @override
  void dispose() {
    super.dispose();
    notesController.dispose();
    notesFocusNode.dispose();
  }

  void onSave() async {
    bool isSuccess = false;

    List<int> attachmentIds = await uploadFiles();
    if (attachmentIds == null) return;

    await post(
        HttpAssetService.disposeAsset(
          id,
          notes: notesController.text,
          disposed_at: DateTimeUtils.formatDateTime(
            disposalDate,
            'yyyy-MM-dd',
          ),
          attachment_ids: attachmentIds,
        ),
        autoHandler: AutoHandler.Toast,
        loadingTip: S.current.loading, onSuccess: (result) {
      isSuccess = true;
    });

    obtainContext?.call((context) {
      Navigator.of(context).pop(true);
      Providers.get<DateReportProvider>(RouterGenProviders.dateReportPage, null)
          .onRequestRefresh();
    });
  }

  void onChangeDisposalDate() {
    obtainContext?.call((context) async {
      disposalDate = await showCalendarBottomSheet(context, disposalDate);
      update();
    });
  }

  @override
  List<OcrAttachmentEntity> get attachments => attachedFiles;

  @override
  void unFocus() {
    FocusManager.instance.primaryFocus.unfocus();
  }
}
